package com.yimu.lib.util;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

import com.yimu.lib.base.BaseActivity;
import com.yimu.lib.http.download.DownLoadImageService;
import com.yimu.lib.http.download.ImageDownLoadCallBack;

import java.io.File;
import java.util.ArrayList;

/**
 * 描述：TODO
 * 创建者：  Churck
 * 创建时间：16/8/31 14:34
 * 修改者： Churck
 * 修改时间：16/8/31 14:34
 * 版 本：v1.0
 */
public class SystemShareUtils {
    public final static String WeChatPkg = "com.tencent.mm";
    public final static String WeChatFriend = "com.tencent.mm.ui.tools.ShareImgUI";//发送给联系人
    public final static String WeChatCollection = "com.tencent.mm.ui.tools.AddFavoriteUI";//添加到收藏
    public final static String WeChatFriendCircle = "com.tencent.mm.ui.tools.ShareToTimeLineUI";// 发送到朋友圈
    public final static String QQPkg = "com.tencent.mobileqq";
    public final static String QQFriend = "com.tencent.mobileqq.activity.JumpActivity";
    private String msgText;
    private String imagurl;
    private Context context;
    private StstemShareCallback callback;
    private  boolean checkApp( String apkpag) {
        if (!AppUtils.checkLocalAppExistOrNot(context, apkpag)) {
            if (apkpag.equals(WeChatPkg)) {
                Toast.makeText(context,"请检查是否安装最新版本微信",Toast.LENGTH_LONG).show();
                return true;
            } else if (apkpag.equals(QQPkg)) {
                Toast.makeText(context,"请检查是否安装最新版本QQ",Toast.LENGTH_LONG).show();
                return true;
            } else {
                Toast.makeText(context,"请检查是否存在分享平台",Toast.LENGTH_LONG).show();
                return true;

            }
        }
        return false;
    }
    private  void shareImageandtext(String apkfile, String mApkpag, String mApkpagpath) {
        MyLogger.d("分享图片路径:"+apkfile);
        if (checkApp( mApkpag)) return;
        Intent intent = new Intent();
        ComponentName comp = new ComponentName(mApkpag,mApkpagpath);
        intent.setComponent(comp);
        intent.setAction(Intent.ACTION_SEND);
        File f = new File(apkfile);
        intent.setType("image/jpg");
        Uri u = Uri.fromFile(f);
        intent.putExtra(Intent.EXTRA_STREAM, u);//uri为你要分享的图片的uri
        intent.putExtra("Kdescription", msgText);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        try {
            context.startActivity(intent);
            if (null!=callback)
                callback.startActivityonSucceed(2);
        }catch (Exception e){
            callback.startactivityonFailed();
            checkApp(mApkpag);
        }

    }
    //分享文字
    private   void shareText(String mApkpag, String mApkpagpath) {
        if (checkApp( mApkpag)) return;
        Intent shareIntent = new Intent();
        ComponentName comp = new ComponentName(mApkpag,mApkpagpath);
        shareIntent.setComponent(comp);
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_TEXT, msgText);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        shareIntent.setType("text/plain");
        try {
            context.startActivity(shareIntent);
            if (null!=callback)
                callback.startActivityonSucceed(1);
        }catch (Exception e){
            callback.startactivityonFailed();
            checkApp( mApkpag);
        }
    }


    public void shareinit(BaseActivity mContext, String url, String mText){
        msgText=mText;
        imagurl=url;
        context=mContext;
    }
    public void shareinit( BaseActivity mContext,String url,String mText,StstemShareCallback callback){
        msgText=mText;
        imagurl=url;
        context=mContext;
        this.callback=callback;
    }

    /**
     * 分享
     *   WeChatPkg = "com.tencent.mm";
     WeChatFriend = "com.tencent.mm.ui.tools.ShareImgUI";//发送给联系人
      WeChatCollection = "com.tencent.mm.ui.tools.AddFavoriteUI";//添加到收藏
     WeChatFriendCircle = "com.tencent.mm.ui.tools.ShareToTimeLineUI";// 发送到朋友圈
     QQPkg = "com.tencent.mobileqq";
     QQFriend = "com.tencent.mobileqq.activity.JumpActivity";
     *
     *
     * @param mApkpag apk的包名
     * @param mApkpagpath 分享的类名
     */
    public void doshare(String mApkpag, String mApkpagpath)  {
        if (context==null){
            try {
                throw new Exception("先要初始化shareinit()");
            } catch (Exception e) {
            }finally {
                return;
            }
        }

        if (mApkpagpath.equals(SystemShareUtils.WeChatFriend)){
            shareText(mApkpag,mApkpagpath);
        }else {
            File savefile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator+getFileName(imagurl));
            MyLogger.d("分享图片设置路径:"+savefile.getAbsolutePath());
            if (savefile.exists()){
                shareImageandtext(savefile.getAbsolutePath(),mApkpag,mApkpagpath);
            }else {
                downloadshare( savefile, mApkpag,  mApkpagpath);
            }

        }
    }
    /**
     * 获取文件名
     * @param url  文件地址
     * @return 文件名
     */
    private static String getFileName(String url) {
        String imageName = url.substring(url.lastIndexOf("/") + 1, url.length());
        return imageName;
    }
    private void downloadshare(File file,  String mApkpag,  String mApkpagpath) {
        if (!mApkpagpath.equals(SystemShareUtils.WeChatFriendCircle)){
            shareText(mApkpag, mApkpagpath);
        }else {
            onDownLoad(imagurl,mApkpag,mApkpagpath);

        }
    }
    private void onDownLoad(String url,final String mApkpag, final String mApkpagpath) {
        DownLoadImageService service = new DownLoadImageService(context,
                url,
                new ImageDownLoadCallBack() {
                    @Override
                    public void onDownLoadSuccess(final File file) {
                        MyLogger.d("下载图片path"+file.getAbsolutePath());

                        UIHandler.get().post(new Runnable() {
                            @Override
                            public void run() {
                                MyLogger.d("path"+file.getAbsolutePath());
                                shareImageandtext(file.getAbsolutePath(),mApkpag,mApkpagpath);
                            }
                        });

                    }
                    @Override
                    public void onDownLoadSuccess(Bitmap bitmap) {


                    }

                    @Override
                    public void onDownLoadFailed() {

                    }
                });
        //启动图片下载线程
        new Thread(service).start();
    }

    /**
     * 分享多图到朋友圈，多张图片加文字
     * @param context 上下文
     * @param msgText 分享内容
     * @param apkpag 包名
     * @param apkpagpath 分享类名
     * @param uris 图片地址
     */
    public void shareToTimeLine(Context context,  String msgText, String apkpag, String apkpagpath, ArrayList<Uri> uris) {
        if (checkApp(apkpag)) return;
        Intent intent = new Intent();
        ComponentName comp = new ComponentName(apkpag, apkpagpath);
        intent.setComponent(comp);
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, uris);//uri为你要分享的图片的uri
        intent.putExtra("Kdescription", msgText);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            context.startActivity(intent);
            callback.startActivityonSucceed(2);
        }catch (Exception e){
            checkApp(apkpag);
            callback.startactivityonFailed();
        }
    }

    public interface StstemShareCallback {
        void  startActivityonSucceed(int type);
        void startactivityonFailed();
    }

}
